package com.tsx.dictionary.utils;

import com.tsx.dictionary.enums.GenderEnum;

import java.lang.reflect.Field;
import java.util.function.Function;

public class FieldHelper {

    public static <T, R> Function<T, R> getFieldFunction(String fieldName) {
        return (T obj) -> {
            try {
                Field field = obj.getClass().getDeclaredField(fieldName);
                field.setAccessible(true);
                return (R) field.get(obj);
            } catch (NoSuchFieldException | IllegalAccessException e) {
                throw new RuntimeException("无法获取字段: " + fieldName, e);
            }
        };
    }

    public static void main(String[] args) {
        GenderEnum male = GenderEnum.Male;
        Function<Object, Object> function = FieldHelper.getFieldFunction("code");
        System.out.println("function = " + function);
        System.out.println(function.apply(male)); // code
        System.out.println(FieldHelper.getFieldFunction("desc").apply(male));   // desc
    }
}
